<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>新建合同</title>
    <link rel="stylesheet" href="../../lib/layui/layui/css/layui.css">
    <link rel="stylesheet" href="../../lib/layui/css/layui.css">
    <script type="text/javascript" src="../../js/news/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="../../lib/layui/layui/lay/dest/layui.all.js"></script>
    <script src="../../js/base/base.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../lib/layui/layui/layui.js"></script>
    <style>
        * {
            font-family: "Microsoft Yahei" !important;
        }

        .layui-inline b {
            color: red;
        }

        nav button {
            margin-left: 5px;
            padding: .25rem .5rem;
            font-size: .875rem;
            border-radius: .2rem;
            float: right !important;
            margin-top: 10px
        }

        nav div {
            float: left !important;
            margin: 15px;
        }

        nav {
            height: 50px;
            border-bottom: 1px solid #cfdbe2;
            background-color: #fafbfc;
            border-radius: 0;
        }

        .layui-tab-title {
            border-bottom: 1px solid #cfdbe2;
            background-color: #fafbfc;
        }

        .layui-tab {
            margin: 0;
        }

        .content {
            height: 509px;
            overflow: auto;
            margin: 14px;
            padding: 14px;
            background: #fff;
        }

        .layui-tab-content {
            background-color: #F5F7FA;
        }

        .search {
            display: inline;
            margin-bottom: 1px;
            padding-top: 6px;
            padding-bottom: 6px;
            width: 185px;
            border: 0;
        }

        .layui-form-label {
            width: 150px;
        }

        .spanUser {
            margin-top: 25px;
            display: inline-block;
            margin-right: 5px;
            background: #e8e8e8;
            color: #333;
            border-radius: 30px;
            line-height: 27px;
            padding-left: 20px;
            padding-right: 20px;
            position: relative;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .spanText {
            margin-top: 25px;
            display: inline-block;
            margin-right: 5px;
            background: #e8e8e8;
            color: #333;
            border-radius: 30px;
            line-height: 27px;
            padding-left: 20px;
            padding-right: 20px;
            position: relative;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .layui-form-select {
            overflow: visible;
        }

        .relative {
            background-color: #fff;
            border: 2px solid #ececec;
            border-radius: 6px;
            height: 140px;
            width: 140px;
            overflow: visible;
        }

        .layui-table > tbody div[class*='0-11'] {
            overflow: visible !important;
        }

        #addTableDiv .laytable-cell-1-0-1, .laytable-cell-1-0-4 {
            overflow: visible !important;
        }

        .layui-table-box {
            overflow: visible;
        }

        .layui-table-body {
            overflow: visible;
        }

        td .layui-form-select {
            margin-top: -10px;
        }

        body {
            overflow-y: hidden;
        }

        .addBtn {
            background: #f2f2f2;
            margin: 0px 15px;
            padding: 10px 0;
        }

        .layui-card-body {
            padding: 0 15px;
            margin-top: -10px;
        }
        .bg{
            background-color: #99FFFF;
        }
    </style>
</head>
<body>
<nav>
    <div>新建合同</div>
    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm return" style="margin-right: 30px">
        返回
    </button>
    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm save">
        保存
    </button>
</nav>
<div>
    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
        <ul class="layui-tab-title">
            <li class="layui-this">基本信息</li>
            <li>合同正文</li>
            <li>子合同</li>
            <li>结算情况</li>
            <li>订单</li>
            <li>相关流程</li>
            <li>提醒计划</li>
            <li>附件</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="content">
                    <form class="layui-form" id="ajaxforms" action="/contract/insertContract">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">合同编号</label>
                                <div class="layui-inline" style="width:352px;">
                                    <input type="text" name="contractNo" class="layui-input required layui-disabled contractNo"  disabled>
                                </div><b>*</b>
                                <button type="button" class="layui-btn layui-btn-sm newNum">已取号</button>
                                <button type="button" class="layui-btn layui-btn-sm" name="contractNo">新取号</button>
                            </div>
                            <div class="layui-inline" style="margin-left: 85px;">
                                <label class="layui-form-label" style="width: 76px;">合同标题</label><b>*</b>
                                <div class="layui-input-inline">
                                    <input type="text" name="title" class="layui-input required">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item" style="overflow: visible;">
                            <div class="layui-inline" style="overflow: visible;">
                                <label class="layui-form-label">合同类型</label><b>*</b>
                                <div class="layui-input-inline layui-form" style="overflow: visible;"
                                     lay-filter="mySelect">
                                    <select id="contractType" class="required" lay-verify="required"
                                            lay-filter="warehouse">

                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline" style="margin-left: -8px;">
                                <label class="layui-form-label">合同种类</label>
                                <div class="layui-input-inline">
                                    <div class="layui-input-inline layui-form" style="overflow: visible" lay-filter="mySelect">
                                        <select  lay-verify="required" lay-filter="contract_type" name="contract_type" id="contract_type">
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">合同对象</label><b>*</b>
                                <div class="layui-input-inline">
                                    <input type="text" name="targetName" class="layui-input required">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label">主合同</label>
                                <div class="layui-input-inline;" id="masterContract" style="display:inline">
                                    <input type="text" style="border-bottom: 1px solid #ccc;" class="search parent"
                                           placeholder="搜索" readonly/>
                                    <span style="padding: 5px;color: #999;cursor: pointer;margin-left:-26px"><i
                                            class="layui-icon layui-icon-username master"></i></span>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label" >合同金额</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="money" class="layui-input" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" >
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">金额大写</label>
                                <div class="layui-input-inline">
                                    <input style="border: none" type="text" name="moneyCp" class="layui-input" disabled>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方</label>
                                <div class="layui-input-inline" >
                                    <input type="text" name="aUser" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bUser" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方地址</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="aAddress" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方地址</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bAddress" class="layui-input">
                                </div>
                            </div>

                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方联系人</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="aLinkman" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方联系人</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bLinkman" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方电话</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="aPhone" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方电话</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bPhone" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方签字</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="aSign" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方签字</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bSign" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">甲方签字日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="aSignTime" id="aSignTime" lay-verify="date"
                                           placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">乙方签字日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="bSignTime" id="bSignTime" lay-verify="date"
                                           placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">授权日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="date_comment" id="authorization" lay-verify="date"
                                           placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" style="margin-right: 8px;">授权代表</label>
                                <div class="layui-input-inline"  style="margin-left: -9px">
                                    <input type="text" name="authorized_representative"  class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">合同工期开始日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="duration_startdate" id="begins" lay-verify="date"
                                           placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">合同工期结束日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="duration_enddate" id="endtime" lay-verify="date"
                                           placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">对方单位</label>
                                <div class="layui-input-inline">
                                    <input type="radio" name="othersideunit" value="1" title="甲方" checked="">
                                    <input type="radio" name="othersideunit" value="2" title="乙方">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" >执行单位</label>
                                <div class="layui-input-inline">
                                    <div class="layui-input-inline layui-form" style="overflow: visible;" lay-filter="mySelect">
                                        <select  lay-verify="required" lay-filter="executive_unit" name="executive_unit" id="executive_unit" >
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">所属部门</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="rescueUser" dept_id=""  class="layui-input">
                                </div>
                                <a href="javascript:;" style="color:#1E9FFF" class="addExecute">添加</a>
                                <a href="javascript:;" style="color:#1E9FFF" class="clearExecute">清空</a>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" style="width: 90px;">备注</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="remarks" lay-verify="remarks" autocomplete="off"
                                           placeholder="请输入标题" class="layui-input">
                                </div>
                            </div>

                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">风险评估</label>
                                <div class="layui-input-inline">
                                    <input type="radio" name="risk_assessment" value="0" title="否" checked="">
                                    <input type="radio" name="risk_assessment" value="1" title="是">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label"> 合同评审</label>
                                <div class="layui-input-inline">
                                    <input type="radio" name="contract_approval" value="0" title="否" checked="">
                                    <input type="radio" name="contract_approval" value="1" title="是">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">跟进人</label>
                                <div class="layui-input-block" id="userId"></div>
                            </div>
                            <div class="layui-inline" style="float: right;margin-right: 209px;">
                                <label class="layui-form-label">合同履行地点</label>
                                <div class="layui-input-inline">
                                    <div class="layui-input-inline">
                                        <input type="text" name="do_address" class="layui-input">
                                    </div>
                                </div>
                            </div>

                        </div>
                    </form>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content">
                        <textarea id="texPart" style="display: none;"></textarea>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content" id="local">
                        <span></span>
                        <div style="display: inline-block;border-bottom: 1px solid #ccc;" class="local">
                            <input type="text" readonly class="search" placeholder="搜索"/>
                            <span style="padding: 5px;color: #999;cursor: pointer;">
                                    <i class="layui-icon layui-icon-username localAet"></i>
                                </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content">
                        <div class="layui-card">
                            <div class="addBtn">
                                <button data-type="0" style="margin-left: 15px" type="button" id="addButton"
                                        class="layui-btn layui-btn-sm" lay-event="add"/>
                                添加
                            </div>
                            <div id="addTableDiv" class="layui-card-body">
                                <table class="layui-hide" id="settlementOf" lay-filter="settlementOf"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content">
                        <div class="addBtn">
                            <div data-type="0" style="margin-left: 15px" id="orderButton" class="layui-btn layui-btn-sm"
                                 lay-event="add">添加
                            </div>
                        </div>
                        <div id="orderTableDiv" class="layui-card-body">
                            <table class="layui-hide" id="order" lay-filter="order"></table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content" id="flow" runId="" conTractId="" runName="">
                        <span></span>
                        <div style="display: inline-block;border-bottom: 1px solid #ccc;" class="flow">
                            <input type="text" readonly class="search" placeholder="搜索"/>
                            <span style="padding: 5px;color: #999;cursor: pointer;">
                                    <i class="layui-icon layui-icon-search flowAet"></i>
                                </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content">
                        <div class="addBtn">
                            <div data-type="0" style="margin-left: 15px" id="planButton" class="layui-btn layui-btn-sm"
                                 lay-event="add">添加
                            </div>
                        </div>
                        <div id="planTableDiv" class="layui-card-body">
                            <table class="layui-hide" id="plan" lay-filter="plan"></table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="content">
                        <form class="layui-form" action="">
                            <button type="button" class="layui-btn layui-btn-normal" id="test3"><i
                                    class="layui-icon"></i>上传文件
                            </button>
                        </form>
                        <div style="margin: 20px 0;display: none">
                            <%--<span class="num"><i class="layui-icon layui-icon-link"></i> 1个附件</span>--%>
                            <%-----%>
                            <%--<span style="color:#03a9f4;cursor:pointer" class="everything">下载全部</span>--%>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/html" id="settlementOfDel">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2">删除</a>
    </script>
    <script type="text/html" id="orderDel">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2">删除</a>
    </script>
    <script type="text/html" id="planDel">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2">删除</a>
    </script>
</div>
</body>
<script>
    var data = [];
    var ContractFlow = [];
    var typeId = '';
    var flowStr = [];
    var productName = [];
    var flowStr1 = [];
    $('.layui-input-inline').width($(document.body).width() / 3 - 70);
    $('.layui-input-inline select').width($(document.body).width() / 3);
    $('.content').height($(window).height() - 130);

    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);

        if (r != null) {
            return unescape(r[2]);
        } else {
            return null;
        }
    }

    $('[name="money"]').on("change", function () {
        var money = $('[name="money"]').val();
        var fraction = ['角', '分'];
        var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
        var head = money < 0 ? '欠' : '';
        money = Math.abs(money);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        money = Math.floor(money);
        for (var i = 0; i < unit[0].length && money > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && money > 0; j++) {
                p = digit[money % 10] + unit[1][j] + p;
                money = Math.floor(money / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        var sum = head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
        $('[name="moneyCp"]').val(sum);
    })

    $(function () {
        $.ajax({
            url: '/portals/selPortalsUser',
            type: 'get',
            dataType: 'json',
            success: function (data) {
                $('#userId').html('<span class="spanUser" userId=' + data.object.userId + ' style="margin-top: 7px">' + data.object.userName + '</span>')
            }
        });
    });

    function nonEmpty(num) {
        if (num == '' || num == undefined) {
            return ''
        } else {
            return num
        }
    }

    $('.return').click(function () {
        history.go(-1)
    })

    layui.use(['form', 'layedit', 'laydate', 'table', 'upload','layer'], function () {
        var form = layui.form
            , layer = layui.layer
            , laydate = layui.laydate
            , layedit = layui.layedit
            , table = layui.table
            , layer = layui.layer
            , upload = layui.upload;

        var conNumber //定义已取号的变量
        var isNo

        var index = layedit.build('texPart'); //建立编辑器

        $.ajax({
            url: '/contract/selectTypeAll',
            type: 'get',
            dataType: 'json',
            success: function (data) {
                var str = '<option></option>';
                for (var i = 0; i < data.data.length; i++) {
                    str += '<option value="' + data.data[i].typeId + '">' + data.data[i].typeName + '</option>'
                }
                $('#contractType').append(str);
                $('.layui-unselect .layui-form-select .layui-form-selected').css("overflow", "visible")
                form.render('select');
            }
        });

        //合同种类
        $.ajax({
            url:'/code/getCode',
            type: 'get',
            dataType: 'json',
            data:{
                parentNo:'CONTRACT_TYPE'
            },
            success:function (res) {
                var str = '<option></option>';
                for (var i = 0; i <res.obj.length; i++) {
                    str += '<option value="' + res.obj[i].codeNo + '">' + res.obj[i].codeName + '</option>'
                }
                $('#contract_type').append(str);
                form.render('select');
            }
        })
        //执行单位
        $.ajax({
            url:'/code/getCode',
            type: 'get',
            dataType: 'json',
            data:{
                parentNo:'CONTRACT_UNIT'
            },
            success:function (res) {
                var str = '<option></option>';
                for (var i = 0; i <res.obj.length; i++) {
                    str += '<option value="' + res.obj[i].codeNo + '">' + res.obj[i].codeName + '</option>'
                }
                $('#executive_unit').append(str);
                form.render('select');
            }
        })

        form.on('select(warehouse)', function (data) {
            typeId = $('#contractType').val()  //获取下拉框的value值
        });

        //日期
        laydate.render({
            elem: '#aSignTime'
            , type: 'datetime'
        });

        laydate.render({
            elem: '#invoiceTime'
        });

        laydate.render({
            elem: '#bSignTime'
            , type: 'datetime'
        });
        laydate.render({
            elem: '#authorization'
            , type: 'datetime'
        });
        laydate.render({
            elem: '#begins'
            , type: 'datetime'
        });
        laydate.render({
            elem: '#endtime'
            , type: 'datetime'
        });

        //进货人点击添加的按钮
        $(".addExecute").on("click",function(){
            dept_id = 'rescueUser';
            $.popWindow("/common/selectDept?0");
        });

        $('.clearExecute').click(function () {
            $('#rescueUser').attr('dept_id','');
            $('#rescueUser').attr('deptid','');
            $('#rescueUser').val('');
        });

        //指定允许上传的文件类型
        var fileObj = {};
        fileObj.attachmentId = '';
        fileObj.attachmentName = '';
        upload.render({
            elem: '#test3'
            , url: '../upload?module=contract'
            , multiple: true
            , accept: 'file' //普通文件
            , done: function (res) {
                var str = '';
                if (res.flag) {
                    fileObj.attachmentId += res.obj[0].aid + '@' + res.obj[0].ym + '_' + res.obj[0].attachId + ',';
                    fileObj.attachmentName += res.obj[0].attachName + '*';
                    str += '<div style="display:inline-block;margin-right: 25px" class="fileDiv"><div class="relative">' +
                        '   <i class="layui-icon layui-icon-close close"  style="float: right;"></i>' +
                        '  <i class="layui-icon layui-icon-list file" id="file"  deurl="' + res.obj[0].attUrl + '" name="' + res.obj[0].attachName + '"  style="font-size: 30px;font-size: 100px; padding-left: 20px;line-height: 140px;"></i>' +
                        '  </div>' +
                        '  <div style="margin:10px;" class="fileName">' + res.obj[0].attachName + '(' + res.obj[0].fileSize + ')' + '</div></div>';
                    $('.content').last().append(str);
//                    $('.num').html('<i class="layui-icon layui-icon-link" style="margin-right:6px"></i>'+$('.fileName').length+'个附件')
                    $('#test3').parent().siblings('div').show();
                    $('#file').click(function () {
                        window.location = "../../download?" + res.obj[0].attUrl;
                    });
                    $('.close').click(function () {
                        $(this).parents('.fileDiv').remove();
                    })
                }
            }
        });

        var runId = '';
        table.render({
            elem: '#settlementOf'
            , data: data
            , cols: [[
                {field: 'sort', title: '序号', type: 'numbers',}
                , {
                    field: 'projectType', title: '款项性质', event: 'projectType', templet: function (d) {
                        return '<select class="projectType" lay-filter="projectType" lay-verify="required" >\n' +
                            '<option value=""></option>\n' +
                            '<option value="0">收入</option>\n' +
                            '<option value="1">支出</option>\n' +
                            '      </select>';
                    }
                }
                , {field: 'payType', title: '款项类别', edit: true}
                , {field: 'money', title: '款项金额（元）', edit: true}
                , {
                    field: 'payWay', title: '打款方式', event: 'payWay', templet: function (d) {
                        // 模板的实现方式也是多种多样，这里简单返回固定的
                        return '<select class="payWay" lay-filter="payWay" lay-verify="required" >\n' +
                            '<option value=""></option>\n' +
                            '<option value="01">现金</option>\n' +
                            '<option value="02">转账</option>\n' +
                            '<option value="03">支票</option>\n' +
                            '<option value="04">支付宝</option>\n' +
                            '<option value="05">微信</option>\n' +
                            '<option value="06">其他</option>\n' +
                            '      </select>';
                    }
                }
                , {field: 'payAccount', title: '打款账号', edit: true}
                , {field: 'payTime', title: '打款时间', event: 'date', data_field: "dDate"}
                , {field: 'invoiceTime', title: '开票时间', event: 'date', data_field: "dDate"}
                , {
                    field: 'runId', width: 300, title: '关联流程', templet: function (d) {
                        return '<div  id="flowTab">' +
                            ' <span></span>' +
                            ' <div style="display: inline-block;border-bottom: 1px solid #ccc;" class="flowTab">' +
                            '<input type="text" readonly class="search" placeholder="搜索"/>' +
                            '<span style="padding: 5px;color: #999;cursor: pointer;">' +
                            '<i class="layui-icon layui-icon-search flow-Tab"></i>' +
                            ' </span>' +
                            ' </div>' +
                            ' </div>'
                    }
                }
                , {field: 'remarks', title: '备注', edit: true}
                , {title: '操作', align: 'center', toolbar: '#settlementOfDel'}
            ]]
            , page: true
            , done: function (res, curr, obj) {
                $('.laytable-cell-1-0-8').css("display", "inherit")
                $('.flow-Tab').click(function () {
                    var num = $('.flow-Tab').index(this)
                    var flowTab = '#flowTab' + num;
                    var runIds = [];
                    for (var i = 0; i < $('#flowTab' + num).find('.flowase').length; i++) {
                        runIds += $('#flowTab' + num).find('.flowase').eq(i).attr('runId') + ',';
                    }
                    $(this).parents('#flowTab').attr('id', 'flowTab' + num)
                    layer.open({
                        type: 1,
                        title: ['选择流程'],
                        area: ['750px', '640px'],
                        shadeClose: true, //点击遮罩关闭
                        content: '<div>' +
                            '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;line-height: 30px" placeholder="请输入流程的标题"/><i class="layui-icon layui-icon-search flowIcon" style="margin-left: -30px"></i></div>' +
                            '<div style="margin:0 20px 0 20px;">' +
                            '<table class="layui-hide" id="flowTable"></table>' +
                            '</div>',
                        btn: ['确定']
                        , success: function (data) {
                            table.render({
                                elem: '#flowTable'
                                , url: '/workflow/work/selectAll?page=1&pageSize=20&useFlag=true'
                                , page: true
                                , cols: [[
                                    {type: 'checkbox', fixed: 'left'}
                                    , {field: 'runName', title: '流程标题',templet:function (d) {
                                            return d.flowRun.runName
                                        }}
                                    , {field: 'userName', title: '创建人'}
                                    , {field: 'createTime', title: '创建时间'}
                                ]]
                                , parseData: function (res) { //res 即为原始返回的数据
                                    return {
                                        "code": 0, //解析接口状态
                                        "data": res.obj //解析数据列表
                                    };
                                }
                                , done: function (obj) {
                                    $("[data-field='id']").css('display', 'none');
                                    var data = obj.data;
                                    for (var i = 0; i < data.length; i++) {
                                        if (runIds.indexOf(String(data[i].runId)) > -1) {
                                            var index = data[i]['LAY_TABLE_INDEX'];
                                            $('div[lay-id="flowTable"] tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                            $('div[lay-id="flowTable"] tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                            data[i].LAY_CHECKED = true;
                                        }
                                    }
                                }
                            });
                            $('.flowIcon').click(function () {
                                var search = $(this).siblings('input').val()
                                if ($('.search') != '') {
                                    table.reload('flowTable', {
                                        url: '/contract/selectFlowBy',
                                        method: 'post',
                                        where: {
                                            cha: search
                                        }
                                    })
                                }
                            });
                        },
                        yes: function (index) {
                            var checkStatus = table.checkStatus('flowTable')  // 打开页面中的table ID
                                , data = checkStatus.data;     //  这个data一直为 []
                            if (data != '') {
                                var flowName = '';
                                var runId = ''
                                for (var i = 0; i < $('#flowTab' + num).find('.flowSpan').length; i++) {
                                    runId += $('#flowTab' + num).find('.flowSpan').eq(i).attr('runid') + ','
                                }
                                for (var i = 0; i < data.length; i++) {
                                    if (runId.indexOf(data[i].runId) == -1) {
                                        flowName += '<span style="margin-top: 0" runId="' + nonEmpty(data[i].runId) + '" class="spanText flowSpan flowase">' + data[i].flowRun.runName + '<a title="取消" num=' + [i] + ' class="flowcancelTab" style="cursor: pointer;color: darkgrey;padding-left:10px">×</a></span><br>'
                                    }
                                }
                                $('#flowTab' + num).children('span').append(flowName)
                                $(document).on('click', '.flowcancelTab', function () {
                                    $(this).parent('.spanText').next().remove()
                                    $(this).parent('.spanText').remove()
                                    flowStr.push($('#flowTab' + num).html() + "@" + num)
                                });
                                var dataIndex = $('#flowTab' + num).parents('tr').attr("data-index");
                                var field = $('#flowTab' + num).parents('td').attr('data-field');
                                var runIds = ''
                                for (var i = 0; i < $('#flowTab' + num).find('.flowSpan').length; i++) {
                                    runIds += $('#flowTab' + num).find('.flowSpan').eq(i).attr('runid') + ','
                                }
                                table.cache["settlementOf"][dataIndex][field] = runIds
                                flowStr.push($('#flowTab' + num).html() + "@" + num)
                                layer.close(index)
                            }
                        }
                    })
                })


            }
        });

        var orderRunId = ''
        var productId = ''
        //第一个表格的工具事件
        table.on('tool(settlementOf)', function (obj) {
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr;
            var data = obj.data;
            var newdata = {};
            if (layEvent === 'date') {
                var field = $(this).data('field');
                var index = tr.attr("data-index");
                laydate.render({
                    elem: this.firstChild
                    , show: true //直接显示
                    , closeStop: this
                    , type: 'datetime'
                    , done: function (value, date) {
                        table.cache["settlementOf"][index][field] = value
                    }
                });
            }
            if (layEvent == 'payWay') {
                var index = tr.attr("data-index");
                var field = $(this).data('field');
                form.on('select(payWay)', function (data) {
                    table.cache["settlementOf"][index][field] = data.value
                });
            }
            if (layEvent == 'projectType') {
                var index = tr.attr("data-index");
                var field = $(this).data('field');
                form.on('select(projectType)', function (data) {
                    table.cache["settlementOf"][index][field] = data.value
                });
            }
            if (layEvent == 'del2') {
                var index = tr.attr("data-index");
                obj.del(tr);
                data = table.cache["settlementOf"];
                data.splice(parseInt(index), 1);
                table.reload('settlementOf', {
                    data: data
                });
                for (var i = 0; i < flowStr.length; i++) {
                    $('.flowTab').eq(flowStr[i].split("@")[1]).parent().html(flowStr[i].split("@")[0])
                }
                for (var i = 0; i < data.length; i++) {
                    var select = 'dd[lay-value=' + data[i].projectType + ']';
                    $('.projectType').eq(i).siblings("div .layui-form-select").find('dl').find(select).click()
                    var payWay = 'dd[lay-value=' + data[i].payWay + ']';
                    $('.payWay').eq(i).siblings("div .layui-form-select").find('dl').find(payWay).click()
                    form.render();
                }
                var trs = $("#addTableDiv").find(".layui-table-body").find("tr");
            }

        });

        table.render({
            elem: '#order'
            , data: data
            , cellMinWidth: 80
            , cols: [[
                {field: 'sort', title: '序号', type: 'numbers',}
                , {
                    field: 'productId', title: '产品名称', templet: function (d) {
                        return ' <div class="layui-input-inline productName"  style="display:inline;border-bottom: 1px solid #ccc">' +
                            '<input type="text" style="border-bottom: 1px solid #ccc;width: 150px;padding-bottom:2px" readonly class="search productSea" placeholder="搜索"/>' +
                            '<span style="padding: 5px;color: #999;cursor: pointer;margin-left:-26px"><i class="layui-icon layui-icon-username product"></i></span>' +
                            '</div>'
                    }
                }
                , {field: 'shippingDate', title: '发货时间', event: 'date', data_field: "dBeginDate"}
                , {field: 'number', title: '发货数量', edit: true}
                , {
                    field: 'runId', title: '关联流程', width: 300, title: '关联流程', templet: function (d) {
                        return '<div  id="flowOrder">' +
                            ' <span></span>' +
                            ' <div style="display: inline-block;border-bottom: 1px solid #ccc;" class="flowOrder">' +
                            '<input type="text" readonly class="search" placeholder="搜索"/>' +
                            '<span style="padding: 5px;color: #999;cursor: pointer;">' +
                            '<i class="layui-icon layui-icon-search flow-Order"></i>' +
                            ' </span>' +
                            ' </div>' +
                            ' </div>'
                    }
                }
                , {field: 'remarks', title: '备注', edit: true}
                , {title: '操作', align: 'center', toolbar: '#orderDel'}
            ]], done: function () {
                $('.laytable-cell-2-0-4').css("display", "inherit")
                $('.product').click(function () {
                    var num = $('.product').index(this)
                    $(this).parents('.productName').attr('class', 'productName' + num)
                    layer.open({
                        type: 1,
                        title: ['合同选择'],
                        area: ['750px', '640px'],
                        shadeClose: true, //点击遮罩关闭
                        content: '<div>' +
                            '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;height: 30px" placeholder="请输入合同的编号及标题"/><i class="layui-icon layui-icon-search flowIcon" style="margin-left: -30px"></i></div>' +
                            '<div style="margin:0 20px 0 20px;">' +
                            '<table class="layui-hide" id="productTable"></table>' +
                            '</div>',
                        btn: ['确定']
                        , success: function (data) {
                            $('.laytable-cell-1-0-1').css("display", "inherit")
                            table.render({
                                elem: '#productTable'
                                , url: '/product/selectProduct'
                                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                                , cols: [[
                                    {type: 'radio'}
                                    , {field: 'productId', title: '产品编号'}
                                    , {field: 'productName', title: '产品名称'}
                                    , {field: 'meteringUnit', title: '产品单位 '}
                                ]]
                                , page: true
                                , parseData: function (res) { //res 即为原始返回的数据
                                    return {
                                        "code": 0, //解析接口状态
                                        "data": res.obj //解析数据列表
                                    };
                                }
                            });
                            $('.flowIcon').click(function () {
                                var search = $(this).siblings('input').val()
                                if (search != '') {
                                    table.reload('productTable', {
                                        url: '/product/selectByConditionProduct',
                                        method: 'post',
                                        where: {
                                            productName: search
                                        }
                                    })
                                }
                            });
                        },
                        yes: function (index) {
                            var checkStatus = table.checkStatus('productTable')  // 打开页面中的table ID
                                , data = checkStatus.data;     //  这个data一直为 []
                            if (data != '') {
                                var str = ''
                                str = '<span class="spanText productId" productId=' + data[0].productId + '  style="margin-top:5px;position:relative">' + data[0].productName + '<a style="color: darkgrey;cursor:pointer;margin-left: 5px;" title="取消" class="cancel">×</a></span>'
                                $('.productName' + num).prepend(str);
                                $('.productName' + num).find('.productSea').hide();
                                $(document).on('click', '.cancel', function () {
                                    $(this).parent('.spanText').siblings('.productSea').show();
                                    $(this).parents('.spanText').remove();
                                    productName.push($('.productName' + num).parent().html() + "@" + num)
                                });
                                productName.push($('.productName' + num).parent().html() + "@" + num)

                                var dataIndex = $('.productName' + num).parents('tr').attr("data-index");
                                var field = $('.productName' + num).parents('td').attr('data-field');
                                var productId = ''
                                for (var i = 0; i < $('.productName' + num).find('.spanText').length; i++) {
                                    productId += $('.productName' + num).find('.spanText').eq(i).attr('productId') + ','
                                }
                                table.cache["order"][dataIndex][field] = productId
                                layer.close(index)
                            }
                        }
                    })
                })
                $('.flow-Order').click(function () {
                    var num = $('.flow-Order').index(this)
                    $(this).parents('#flowOrder').attr('id', 'flowOrder' + num)
                    var flowOrder = '#flowOrder' + num
                    var runId = []
                    for (var i = 0; i < $('#flowOrder' + num).find('.flowIndent').length; i++) {
                        runId.push($('#flowOrder' + num).find('.flowIndent').eq(i).attr('runId'))
                    }
                    layer.open({
                        type: 1,
                        title: ['选择流程'],
                        area: ['750px', '640px'],
                        shadeClose: true, //点击遮罩关闭
                        content: '<div>' +
                            '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;line-height: 30px" placeholder="请输入流程的标题"/><i class="layui-icon layui-icon-search flowIcon" style="margin-left: -30px"></i></div>' +
                            '<div style="margin:0 20px 0 20px;">' +
                            '<table class="layui-hide" id="orderTable"></table>' +
                            '</div>',
                        btn: ['确定']
                        , success: function (data) {
                            table.render({
                                elem: '#orderTable'
                                , url: '/workflow/work/selectAll?page=1&pageSize=20&useFlag=true'
                                , page: true
                                , cols: [[
                                    {type: 'checkbox', fixed: 'left'}
                                    , {field: 'runName', title: '流程标题',templet:function (d) {
                                            return d.flowRun.runName
                                        }}
                                    , {field: 'userName', title: '创建人'}
                                    , {field: 'createTime', title: '创建时间'}
                                ]]
                                , parseData: function (res) { //res 即为原始返回的数据
                                    return {
                                        "code": 0, //解析接口状态
                                        "data": res.obj //解析数据列表
                                    };
                                }
                                , done: function (res, curr, count) {
                                    $("[data-field='id']").css('display', 'none');
                                    var data = res.data;
                                    for (var i = 0; i < data.length; i++) {
                                        if (runId.indexOf(String(data[i].runId)) > -1) {
                                            var index = data[i]['LAY_TABLE_INDEX'];
                                            $('div[lay-id="orderTable"] tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                            $('div[lay-id="orderTable"] tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                            data[i].LAY_CHECKED = true;
                                        }
                                    }
                                }
                            });
                            $('.flowIcon').click(function () {
                                var search = $(this).siblings('input').val()
                                if (search != '') {
                                    table.reload('orderTable', {
                                        url: '/contract/selectFlowBy',
                                        method: 'post',
                                        where: {
                                            cha: search
                                        }
                                    })
                                }
                            });
                        },
                        yes: function (index) {
                            var checkStatus = table.checkStatus('orderTable')  // 打开页面中的table ID
                                , data = checkStatus.data;     //  这个data一直为 []
                            if (data != '') {
                                var flowName = ''
                                for (var i = 0; i < data.length; i++) {
                                    if (runId.indexOf(String(data[i].runId)) == -1) {
                                        flowName += '<span style="margin-top: 0" runId=' + nonEmpty(data[i].runId) + ' class="spanText flowSpan flowIndent">' + data[i].flowRun.runName + '<a title="取消" num=' + [i] + ' class="flowcancelOrder" style="cursor: pointer;color: darkgrey;padding-left:10px">×</a></span><br>'

                                    }
                                }
                                $('#flowOrder' + num).children('span').append(flowName)
                                $(document).on('click', '.flowcancelOrder', function () {
                                    $(this).parent('.spanText').next().remove()
                                    $(this).parent('.spanText').remove()
                                    flowStr1.push($('#flowOrder' + num).html() + "@" + num)
                                });
                                flowStr1.push($('#flowOrder' + num).html() + "@" + num)

                                var dataIndex = $('#flowOrder' + num).parents('tr').attr("data-index");
                                var field = $('#flowOrder' + num).parents('td').attr('data-field');
                                var runIds = ''
                                for (var i = 0; i < $('#flowOrder' + num).find('.flowSpan').length; i++) {
                                    runIds += $('#flowOrder' + num).find('.flowSpan').eq(i).attr('runid') + ','
                                }
                                table.cache["order"][dataIndex][field] = runIds
                                layer.close(index)
                            }
                        }
                    })
                })
            }
            , page: true
        });

        //第二个表格的工具事件
        table.on('tool(order)', function (obj) {
            var layEvent = obj.event; //获得 lay-event 对应的值
            var datatr = obj.data;//获取行数据
            var tr = obj.tr;
            var me = $(this);
            var newdata = {};
            var data = obj.data;
            if (obj.event === 'date') {
                var field = $(this).data('field');
                var index = tr.attr("data-index");
                laydate.render({
                    elem: this.firstChild
                    , show: true //直接显示
                    , closeStop: this
                    , done: function (value, date) {
                        table.cache["order"][index][field] = value
                    }
                });
            }
            if (layEvent == 'del2') {
                var index = tr.attr("data-index");
                obj.del(tr);
                data = table.cache["order"];
                data.splice(parseInt(index), 1);
                table.reload('order', {
                    data: data
                });
                for (var i = 0; i < productName.length; i++) {
                    $('.productName').eq(productName[i].split("@")[1]).html(productName[i].split("@")[0])
                }
                for (var i = 0; i < flowStr1.length; i++) {
                    if (flowStr1[i].split("@")[0] != 'undefined') {
                        $('.flowOrder').eq(flowStr1[i].split("@")[1]).parent().html(flowStr1[i].split("@")[0])
                    }
                }
                var trs = $("#orderTableDiv").find(".layui-table-body").find("tr");
            }

        });

        table.render({
            elem: '#plan'
            , data: data
            , cellMinWidth: 80
            , cols: [[
                {field: 'sort', title: '序号', type: 'numbers',}
                , {
                    field: 'userId', title: '提醒对象', templet: function () {
                        return '<div class="username"><input id="governor" type="text" name="parentId" style="border-bottom: 1px solid #ccc;background: white" class="search" readonly placeholder="搜索用户"/>' +
                            '<span style="padding: 5px;color: #999;cursor: pointer;margin-left:-26px"><i class="layui-icon layui-icon-username remind"></i></span>' +
                            '</div></div>'
                    }
                }
                , {field: 'remindDate', title: '提醒日期', event: 'remindDate', data_field: "dBeginDate"}
                , {field: 'content', title: '提醒内容', edit: true}
                , {field: 'remarks', title: '备注', edit: true}
                , {title: '操作', align: 'center', toolbar: '#planDel'}
            ]]
            , page: true
            , done: function () {
                $('.remind').click(function () {
                    var num = $('.remind').index(this)
                    $(this).parents('.username').children('input').attr('id', 'governor' + num)
                    user_id = 'governor' + num;
                    $.popWindow("/common/selectUser?0");
                });
            }
        });

        //第三个表格的工具事件
        table.on('tool(plan)', function (obj) {
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr;
            var newdata = {};
            var data = obj.data;
            if (layEvent == 'remindDate') {
                var field = $(this).data('field');
                var index = tr.attr("data-index");
                laydate.render({
                    elem: this.firstChild
                    , show: true //直接显示
                    , closeStop: this
                    , done: function (value, date) {
                        table.cache["plan"][index][field] = value
                    }
                });
            }
            if (layEvent == 'del2') {
                var index = tr.attr("data-index");
                obj.del(tr);
                data = table.cache["plan"];
                data.splice(parseInt(index), 1);
                table.reload('plan', {
                    data: data
                });
                var trs = $("#planTableDiv").find(".layui-table-body").find("tr");
                for (var i = 0; i < remindUser.length; i++) {
                    if (remindUser[i].split("@")[0] != 'governor') {
                        $('#governor').eq(remindUser[i].split("@")[0]).val(remindUser[i].split("@")[2])
                        $('#governor').eq(remindUser[i].split("@")[0]).attr('username', remindUser[i].split("@")[2])
                        $('#governor').eq(remindUser[i].split("@")[0]).attr('user_id', remindUser[i].split("@")[1])
                    }
                }
            }
        });

        //新取号事件
        $('button[name="contractNo"]').click(function(){
            layer.open({
                type: 2,
                closeBtn: 2,
                btnAlign: 'c',
                area: ['50%', '70%'],
                content: '/ContractNoView/ContractNumber?display=none',
                btn:['确定','取号','重新编号'],
                yes: function(index, layero){
                    $("#layui-layer-iframe"+index)[0].contentWindow.queding();
                    layer.closeAll();
                    return false;

                },
                btn2: function(index, layero){
                    $("#layui-layer-iframe"+index).contents().find('button[layer1="qunding"]').click();
                    return false;
                },
                btn3: function(index, layero){
                    $("#layui-layer-iframe"+index).contents().find('button[layer2="qunding"]').click();
                    return false;
                }
            });
        });
        //已取号的点击事件
        $('.newNum').click(function(){
            layer.open({
                type: 1,
                title: '已取号',
                area: ['750px', '640px'],
                content:'<div style="margin: 10px"><table id="newNumber" lay-filter="newNumber"></table></div>',
                btn: ['确定','返回'],
                success:function (res) {
                    table.render({
                        elem: '#newNumber'
                        , url: '/ContractNo/findContractNo',
                        where:{
                            userId:'admin'
                        }
                        ,cols: [[
                             {type: 'numbers', title: '序号',align: 'center', width: 200}
                            ,{field: 'contractNo', title: '合同编号', align: 'center'}
                        ]]
                        ,parseData: function(res){ //res 即为原始返回的数据
                            return {
                                "code": 0, //解析接口状态
                                "msg": res.msg, //解析提示文本
                                "count": res.totleNum, //解析数据长度
                                "data": res.obj //解析数据列表

                            };
                        }
                        ,page:true
                    });

                    //监听行单击事件
                    table.on('row(newNumber)', function (obj) {
                        var data=obj.data
                         isNo = data.isNo
                         conNumber = data.contractNo
                        $(this).addClass('bg').siblings().removeClass('bg')
                    });
                },
                yes: function (index) {
                    if(isNo != '0'){
                        layer.msg('改编号已使用！', {icon: 2});
                    }else{
                        $('.contractNo').val(conNumber)
                        layer.closeAll();
                    }
                }
            })
        })

        $('.master').click(function () {
            layer.open({
                type: 1,
                title: ['合同选择'],
                area: ['750px', '640px'],
                shadeClose: true, //点击遮罩关闭
                content: '<div>' +
                    '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;height: 30px" placeholder="请输入合同的编号及标题"/><i class="layui-icon layui-icon-search flowIcon" style="margin-left: -30px"></i></div>' +
                    '<div style="margin:0 20px 0 20px;">' +
                    '<table class="layui-hide" id="flowTable"></table>' +
                    '</div>',
                btn: ['确定']
                , success: function (data) {
                    var parentid = $('#masterContract').find('.parentid').attr('parentid');
                    table.render({
                        elem: '#flowTable'
                        , url: '/contract/selectContractAll'
                        , cellMinWidth: 80
                        , cols: [[
                            {type: 'radio', fixed: 'left'}
                            , {field: 'contractNo', title: '合同编号'}
                            , {field: 'title', title: '合同标题'}
                            , {field: 'aSignTime', title: '创建时间'}
                        ]]
                        , page: false
                        , done: function (res, curr, count) {
                            $("[data-field='id']").css('display', 'none');
                            var data = res.data;
                            for (var i = 0; i < data.length; i++) {
                                if (String(data[i].contractId) === parentid) {
                                    var index = data[i]['LAY_TABLE_INDEX'];
                                    $('div[lay-id="flowTable"] tr[data-index="' + index + '"] input[type="radio"]').prop('checked', true);
                                    $('div[lay-id="flowTable"] tr[data-index="' + index + '"] input[type="radio"]').next().addClass('layui-form-checked');
                                    data[i].LAY_CHECKED = true;
                                }
                            }
                            form.render();
                        }
                    });

                    //搜索点击事件
                    $('.flowIcon').click(function () {
                        var search = $(this).siblings('input').val()
                        if (search != '') {
                            table.reload('flowTable', {
                                url: '/contract/selectContractBy',
                                method: 'get',
                                where: {
                                    cha: search
                                }
                            })
                        }
                    });
                },
                yes: function (index) {
                    var checkStatus = table.checkStatus('flowTable')  // 打开页面中的table ID
                        , data = checkStatus.data;     //  这个data一直为 []
                    if (data != '') {
                        var str = '';
                        for (var i = 0; i < data.length; i++) {
                            $('.spanText').remove();
                            $('.add-item').remove();
                            str = '<span class="spanText parentid" parentid="' + data[i].contractId + '" style="margin-top:5px;position:relative">' + data[i].title + '<a style="color: darkgrey;cursor:pointer;margin-left: 5px;" title="取消" class="cancel">×</a></span>' +
                                '<span class="add-item" style="vertical-align: 7px;"><i class="layui-icon layui-icon-add-circle"></i></span>'
                        }
                        $('.parent').parent().prepend(str);
                        $('.parent').hide();
                        $('.parent').siblings().last().hide();
                        $('.add-item').click(function () {
                            $('.parent').show();
                            $('.parent').siblings().last().show();
                        });
                        $('.cancel').click(function () {
                            $(this).parents('.spanText').remove();
                            $('.add-item').remove();
                            if ($(this).siblings('.spanText').length == 0) {
                                $('.parent').show();
                                $('.parent').siblings().last().show();
                            }
                        });
                        layer.close(index)
                    }
                }
            })
        })

        $('.flowAet').click(function () {
            var runIds = [];
            $('#flow').find('p').each(function (index, element) {
                runIds.push($(element).attr('runid'));
            });
            layer.open({
                type: 1,
                title: ['选择流程'],
                area: ['750px', '640px'],
                shadeClose: true, //点击遮罩关闭
                content: '<div>' +
                    '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;line-height: 30px" placeholder="请输入流程的标题"/><i class="layui-icon layui-icon-search flowIcon" style="margin-left: -30px"></i></div>' +
                    '<div style="margin:0 20px 0 20px;">' +
                    '<table class="layui-hide" id="flowTable"></table>' +
                    '</div>',
                btn: ['确定']
                , success: function (data) {
                    table.render({
                        elem: '#flowTable'
                        , url: '/workflow/work/selectAll?page=1&pageSize=20&useFlag=true'
                        , page: true
                        , cols: [[
                            {type: 'checkbox', fixed: 'left'}
                            , {field: 'runName', title: '流程标题',templet:function (d) {
                                    return d.flowRun.runName
                                }}
                            , {field: 'userName', title: '创建人'}
                            , {field: 'createTime', title: '创建时间'}
                        ]]
                        , parseData: function (res) { //res 即为原始返回的数据
                            return {
                                "code": 0, //解析接口状态
                                "data": res.obj //解析数据列表
                            };
                        }
                        , done: function (res, curr, count) {
                            $("[data-field='id']").css('display', 'none');
                            var data = res.data;
                            for (var i = 0; i < data.length; i++) {
                                if (runIds.indexOf(String(data[i].runId)) > -1) {
                                    var index = data[i]['LAY_TABLE_INDEX'];
                                    $('div[lay-id="flowTable"] tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                    $('div[lay-id="flowTable"] tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                    data[i].LAY_CHECKED = true;
                                }
                            }
                            form.render();
                        }
                    });


                    $('.flowIcon').click(function () {
                        var search = $(this).siblings('input').val()
                        if (search != '') {
                            table.reload('flowTable', {
                                url: '/contract/selectFlowBy',
                                method: 'post',
                                where: {
                                    cha: search
                                }
                            })
                        }
                    });
                },
                yes: function (index) {
                    var checkStatus = table.checkStatus('flowTable')  // 打开页面中的table ID
                        , data = checkStatus.data;     //  这个data一直为 []
                    if (data != '') {
                        var flowName = '';
                        var runId = ''
                        for (var i = 0; i < $('.flowSpanRun').length; i++) {
                            runId += $('.flowSpanRun').eq(i).attr('runId') + ','
                        }
                        var num = {}
                        for (var i = 0; i < data.length; i++) {
                            if (runIds.indexOf(data[i].runId) >= -1) {
                                ContractFlow.push({runId: data[i].runId, runName: data[i].runName})
                                flowName += '<p class="spanText flowSpan flowSpanRun" runId="' + data[i].runId + '">' + data[i].flowRun.runName + '<a title="取消" num=' + [i] + ' class="flowcancel" style="cursor: pointer;color: darkgrey;padding-left:10px">×</a></p>'
                            }
                        }

                        $('.flow').hide();
                        $('#flow span:eq(0)').html('');
                        $('#flow span:eq(0)').append(flowName).append('<span class="add-item" style="vertical-align: 7px;"><i class="layui-icon layui-icon-add-circle"></i></span>');
                        $('.add-item').click(function () {
                            $('.flow').show();
                            $('.add-item').hide();
                        });
                        $('.flowcancel').click(function () {
                            $(this).parents('.spanText').remove();
                            if ($(this).attr('num') == 0) {
                                $('.flow').show();
                                $('.add-item').hide();
                            }
                        });
                        layer.close(index)
                    }
                }
            })
        })

        $('.localAet').click(function () {
            var contractId = '';
            var runIds = [];
            for (var i = 0; i < $('.contract').length; i++) {
                runIds.push($('.contract').eq(i).attr('contractId'));
                contractId += $('.contract').eq(i).attr('contractId') + ','
            }
            layer.open({
                type: 1,
                title: ['合同选择'],
                area: ['750px', '640px'],
                shadeClose: true, //点击遮罩关闭
                content: '<div>' +
                    '<input style="width: 200px;margin:20px 0 0 20px;padding-left: 10px;line-height: 30px" type="text" placeholder="请输入合同编号或标题"/><i class="layui-icon layui-icon-search subIcon" style="margin-left: -45px"></i></div>' +
                    '<div style="margin:0 20px 0 20px;">' +
                    '<table class="layui-hide" id="subcontract"></table>' +
                    '</div>',
                btn: ['确定']
                , success: function (data) {
                    table.render({
                        elem: '#subcontract'
                        , url: '/contract/selectContractZi'
                        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        , cols: [[
                            {type: 'checkbox', fixed: 'left'}
                            , {field: 'contractNo', title: '合同编号'}
                            , {field: 'title', title: '合同标题'}
                            , {field: 'aSignTime', title: '创建时间'}
                        ]]
                        , page: true
                        , done: function (res, curr, count) {
                            $("[data-field='id']").css('display', 'none');
                            var data = res.data;
                            for (var i = 0; i < data.length; i++) {
                                if (runIds.indexOf(String(data[i].contractId)) > -1) {
                                    var index = data[i]['LAY_TABLE_INDEX'];
                                    $('div[lay-id="subcontract"] tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                    $('div[lay-id="subcontract"] tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                    data[i].LAY_CHECKED = true;
                                }
                            }
                            form.render();
                        }
                    });
                    $('.subIcon').click(function () {
                        var search = $(this).siblings('input').val()
                        if (search = '') {
                            table.reload('subcontract', {
                                url: '/contract/selectContractZiBy',
                                method: 'post',
                                where: {
                                    cha: search
                                }
                            })
                        }
                    });
                },
                yes: function (index) {
                    var checkStatus = table.checkStatus('subcontract')  // 打开页面中的table ID
                        , data = checkStatus.data;     //  这个data一直为 []
                    if (data != '') {
                        var str = '';
                        for (var i = 0; i < data.length; i++) {
                            if (contractId.indexOf(data[i].contractId) == -1) {
                                str += '<span class="spanText flowSpan contract" contractId="' + data[i].contractId + '">' + data[i].title + '<a title="取消" num=' + [i] + ' class="flowcancel" style="cursor: pointer;color: darkgrey;padding-left:10px">×</a></span>'
                            }
                        }

                        $('.local').hide();
                        $('#local span:eq(0)').append(str).append('<span class="add-item" style="vertical-align: 7px;"><i class="layui-icon layui-icon-add-circle"></i></span>');
                        $('.add-item').click(function () {
                            $('.local').show();
                            $('.add-item').hide();
                        });
                        $('.flowcancel').click(function () {
                            $(this).parents('.spanText').remove();
                            if ($(this).attr('num') == 0) {
                                $('.local').show();
                                $('.add-item').hide();
                            }
                        });
                        layer.close(index)
                    }
                }
            })
        })

        $('.save').click(function () {
            for (var j = 0; j < $('.username').length; j++) {
                var indexs = $('#governor' + j).parents('tr').attr("data-index");
                var field = $('#governor' + j).parents('td').attr('data-field');
                table.cache["plan"][indexs][field] = $('#governor' + j).attr('user_id')
            }
            //合同基本信息
            var obj = {};
            var ajaxforms = $('#ajaxforms').serializeArray();
            $.each(ajaxforms, function (i, v) {
                obj[v.name] = v.value;
            });
            obj.contractNo = $('.contractNo').val()
            obj.dept_id = $('#rescueUser').attr('deptid')
            obj.attachmentId = fileObj.attachmentId;
            obj.attachmentName = fileObj.attachmentName;
            obj.moneyCp = $('[name="moneyCp"]').val();
            obj.content = layedit.getText(index);
            obj.userId = $('#userId').children().attr('userId');
            var flowSpanId = ''
            for (var i = 0; i < $('#local .flowSpan').length; i++) {
                flowSpanId += $('.flowSpan').eq(i).attr('contractId') + ','
            }
            //子合同
            obj.subContract = flowSpanId;
            //主合同
            var parentid = $('.parentid').attr('parentid');
            if (parentid == undefined) {
                parentid = '';
            }
            obj.parentId = parentid
            obj.typeId = typeId;

            //合同项目
            var ContractProject = table.cache["settlementOf"];
            if (runId != '' && runId != undefined) {
                ContractProject[0]["runId"] = runId;
            }

            var ContractTransport = table.cache["order"];
            if (orderRunId != '' && orderRunId != undefined) {
                ContractTransport[0]["runId"] = orderRunId;
            }
            var ContractRemind = table.cache["plan"];
            if ($('#governor').attr('user_id') != '' && $('#governor').attr('user_id') != undefined) {
                ContractRemind[0]["userId"] = $('#governor').attr('user_id');
            }
            for (var i = 0; i < $('.required').length; i++) {
                if ($('.required').eq(i).val() == '') {
                    var content=$('.required').eq(i).parents('.layui-inline').children('.layui-form-label').text()
                    if(content==''){
                        var content=$('.required').eq(i).parents('.layui-form-item').children('.layui-form-label').text()
                    }
                    $.layerMsg({
                        content: '' + content + '不能为空',
                        icon: 2
                    });
                    return false;
                }
            }
            var data = {
                ContractProject: ContractProject,//结束情况
                ContractTransport: ContractTransport,//订单
                ContractRemind: ContractRemind,//提醒计划
                ContractFlow: ContractFlow,//请假流程
                Contract: obj
            };
            $.ajax({
                url: '/contract/insertContract',
                type: 'post',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data) {
                    if (data.flag) {
                        window.location.href = '/contract/mine';
                        layer.msg('保存成功！', {icon: 6});
                    }
                },
                error: function (data) {
                    layer.msg('保存失败！', {icon: 5});
                    /*添加失败*/
                }
            })
        });

        //添加按钮点击事件
        $("#addButton").click(function () {

            var type = $(this).attr("data-type");
            if (type == "0") { //未点击
                //代表还未点击过添加
                data = [];//置空，默认一个
                table.reload('settlementOf', {
                    data: data
                });
                var $addTable = $("#addTableDiv");//得到第二个实例
                $(this).attr("data-type", "1");
                $("#addButton").click();
            } else {
                data = table.cache["settlementOf"];
                var data1 = {}
                data.push({});
                table.reload('settlementOf', {
                    data: data
                });
                for (var i = 0; i < flowStr.length; i++) {
                    if (flowStr[i].split("@")[0] != 'undefined') {
                        $('.flowTab').eq(flowStr[i].split("@")[1]).parent().html(flowStr[i].split("@")[0])
                    }
                }

                for (var i = 0; i < data.length; i++) {
                    var select = 'dd[lay-value=' + data[i].projectType + ']';
                    $('.projectType').eq(i).siblings("div .layui-form-select").find('dl').find(select).click()
                    var payWay = 'dd[lay-value=' + data[i].payWay + ']';
                    $('.payWay').eq(i).siblings("div .layui-form-select").find('dl').find(payWay).click()
                    form.render();
                }
            }
        });

        //添加按钮点击事件
        $("#orderButton").click(function () {
            var type = $(this).attr("data-type");
            data = table.cache["order"];
            var data1 = {};
            data.push(data1);
            table.reload('order', {
                data: data
            });
            for (var i = 0; i < productName.length; i++) {
                $('.productName').eq(productName[i].split("@")[1]).html(productName[i].split("@")[0])
            }
            for (var i = 0; i < flowStr1.length; i++) {
                if (flowStr1[i].split("@")[0] != 'undefined') {
                    $('.flowOrder').eq(flowStr1[i].split("@")[1]).parent().html(flowStr1[i].split("@")[0])
                }
            }
        });

        //添加按钮点击事件
        var remindUser = [];
        $("#planButton").click(function () {
            var forNum = $(this).parents('.content').find('#planTableDiv').find(".layui-table-body").find("tr").length;
            for (var i = 0; i < forNum; i++) {
                var userId = $(this).parents('.content').find('#planTableDiv').find(".layui-table-body").find("tr").eq(i).find("td").eq(1).find('[name="parentId"]').attr('user_id')
                var id = $(this).parents('.content').find('#planTableDiv').find(".layui-table-body").find("tr").attr('data-index')
                var userName = $(this).parents('.content').find('#planTableDiv').find(".layui-table-body").find("tr").eq(i).find("td").eq(1).find('[name="parentId"]').attr('username')
                remindUser.push(id + '@' + userId + '@' + userName)
            }
            var type = $(this).attr("data-type");
            if (type == "0") { //未点击
                //代表还未点击过添加
                data = [];//置空，默认一个
                table.reload('plan', {
                    data: data
                });
                var $addTable = $("#planTableDiv");//得到第二个实例
                $(this).attr("data-type", "1");
                $("#planButton").click();
            } else {
                data = table.cache["plan"];
                var data1 = {};
                data.push(data1);
                table.reload('plan', {
                    data: data
                });
                for (var i = 0; i < remindUser.length; i++) {
                    if (remindUser[i].split("@")[0] != 'governor') {
                        $('#governor').attr('id', 'governor' + remindUser[i].split("@")[0])
                        $('#governor' + remindUser[i].split("@")[0]).val(remindUser[i].split("@")[2])
                        $('#governor' + remindUser[i].split("@")[0]).attr('username', remindUser[i].split("@")[2])
                        $('#governor' + remindUser[i].split("@")[0]).attr('user_id', remindUser[i].split("@")[1])
                    }
                }
            }
        });
    });
</script>

</html>
